import { createClient, getSrc } from '@/utils/ik/oss/oss.js'

export default {
  data() {
    return {
      client: null,
      imageKey: ""
    }
  },
  computed: {
    token() {
      return this.$store.getters['user/getToken']
    }
  },
  mounted() {
    this.client = createClient()
  },
  methods: {
    /**
     * 上传图片 方法
     * @param file
     * @param callback 成功回调
     * @param failCallback 失败回调
     * @returns {*}
     */
    uploadImageFun(file, callback, failCallback) {
      const key = this.getKey(file.type)
      const header = {
        "x-oss-forbid-overwrite": true,
        "Sec-Fetch-Dest": "image",
        "Sec-Fetch-Mode": "no-cors",
        "Sec-Fetch-Site": "cross-site"
      }
      return this.client.put(key, file, header)
        .then(imgUrl => { // OSS上传
          const imageUrl = getSrc(this.client, key)
          callback(imageUrl)
        })
        .catch(err => {
          failCallback(err)
        })
    },
    /**
     * 获取图片key
     * @param fileType
     */
    getKey(fileType) {
      let type
      switch (fileType) {
        case 'image/jpeg':
          type = 'jpeg'
          break
        case 'image/jpg':
          type = 'jpg'
          break
        case 'image/gif':
          type = 'gif'
          break
        case 'image/png':
          type = 'png'
          break
      }
      this.imageKey = 'test/time=' + new Date().getTime() + '&id=' + this.guidGenerator() + '.' + type// 存储路径，并且给图片改成唯一名字
      return this.imageKey
    },
    /**
     * 签名
     * @returns {string}
     */
    guidGenerator() {
      const S4 = function() {
        return ((1 + Math.random()) * 0X10000 | 0).toString(16).substring(1)
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4())
    }
  }
}
